/**
 * 
 */
package neptune.web.client.view;

import java.util.ArrayList;
import java.util.Iterator;

import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.SimplePanel;

/**
 * Per quanto sia a tutti gli effetti una SuperView, questa classe reimplementa
 * tutti i metodi di una superview adoperando un ArrayList per memorizzare le
 * View. Questa scelta e' dettata dalla necessita' di gestira le View senza
 * appoggiarsi ad un DeckPanel, che nel contesto del ViewManager, mostrava
 * alcune anomalie di funzionamento.
 * 
 * @author Roberto Bifulco [info@robertobifulco.it, robertobifulco.it]
 * 
 */
public class ViewManager extends SuperView {

	static private ViewManager manager = new ViewManager();
	private ArrayList<View> views = new ArrayList<View>(0);
	private View active;
	private SimplePanel viewPanel = new SimplePanel();

	private ViewManager() {
		initWidget(viewPanel);
	}

	static public ViewManager getViewManager() {
		return manager;
	}

	@Override
	public int addView(View view) {
		views.add(view);
		return views.indexOf(view);
	}

	@Override
	public View getActiveView() {
		return active;
	}

	@Override
	public void removeView(String viewToken) {
		for (Iterator<View> iterator = views.iterator(); iterator.hasNext();) {
			View view = (View) iterator.next();
			if (view.getName().equals(viewToken))
				removeView(view);
		}
	}

	@Override
	public void removeView(View view) {
		views.remove(view);
	}

	@Override
	public void setActiveView(String viewToken) {

		String state = HistoryTokenUtils.getStateString(viewToken);
		String[] viewLevels = HistoryTokenUtils.getTokenHierarchy(viewToken);
		String thisLevel = viewLevels[0];
		String newToken = "";

		for (int i = 1; i < viewLevels.length; i++) {
			newToken = HistoryTokenUtils.buildToken(newToken, viewLevels[i]);
		}
		if (state != null && !newToken.equals(""))
			newToken = HistoryTokenUtils.addStateToToken(newToken, state);

		for (Iterator<View> iterator = views.iterator(); iterator.hasNext();) {
			View actualView = (View) iterator.next();
			if (actualView.getName().equals(thisLevel)) {
				active = actualView;
				viewPanel.setWidget(actualView);
				if (!newToken.equals("")) {
					((SuperView) actualView).setActiveView(newToken);
				} else if (state != null) {
					setState(state);
				}
			}
		}
	}

	@Override
	public void setViewContainer(DeckPanel container) {
	}

	@Override
	public View getViewByName(String viewToken) {
		for (Iterator<View> iterator = views.iterator(); iterator.hasNext();) {
			View actualView = (View) iterator.next();
			if (actualView.getName().equals(viewToken)) {
				return actualView;
			}
		}
		return null;
	}

}
